import { defineStore } from 'pinia';

export const useWebsocketStore = defineStore('websocket', {
  state: () => ({
    data: {},
    webSocket: null,
  }),
  actions: {
    // 定义操作或者异步请求
    initWebsocket() {
      this.webSocket = new WebSocket(
        // 此处填写你要连接的ws地址
        'wss://api.pqn.e.dianmic.com/api/open/ws/chat?conversation_id=7436315786072866866'
      )

      //建立连接
      this.webSocket.onopen = function () {
        console.log('通讯开始')
        // 发送心跳防止ws协议自动断联
        setInterval(() => {
          this.webSocket.send('1')
        }, 1000 * 60)
      }

      //接收服务端消息
      this.webSocket.onmessage = function (e) {
        console.log('收到的数据：', e.data)
      }

      // 通讯异常
      this.webSocket.onerror = function () {
        console.log('通讯异常')
      }


      // 关闭连接时回调函数
      this.webSocket.close = function () {
        console.log('连接已断开')
      }
    }
  },
});
